var app = angular.module('myApp.services', []);


//Toast server
app.service('toastService', [function () {
    //
    var service = {};
    var _dm_toast = $(".dm-toast");
    if (!_dm_toast.length) {
        _dm_toast = $('<div class="dm-toast"><div></div></div>');
        $("body").append(_dm_toast);
    }
    var _dmt_content = _dm_toast.find("div");
    var _timer_ = null;

    service.show = function (text, time) {
        clearTimeout(_timer_);
        time = time || 3000;
        _dmt_content.html(text);
        _dm_toast.stop().fadeIn(300);
        _timer_ = setTimeout(function () {
            _dm_toast.stop().fadeOut(500);
        }, time)
    };
    service.hide = function () {
        _dm_toast.stop().fadeOut(500);
    };
    return service;
}]);

//汇总基本常用的 Service
app.service('utilService', ["toastService", "ajaxService", "$ionicLoading", "$ionicModal", "$timeout", "$location", "$ionicPopup", "$ionicActionSheet", "$state", "$stateParams" , "$rootScope",
    function (toastService, ajaxService, $ionicLoading, $ionicModal, $timeout, $location, $ionicPopup, $ionicActionSheet, $state, $stateParams, $rootScope) {
        var service = {};

        //自定义
        service.toastService = toastService;
        service.ajaxService = ajaxService.ajax;

        //系统
        service.$timeout = $timeout;
        service.$location = $location;
        service.$state = $state;
        service.$stateParams = $stateParams;

        //ionic
        service.$ionicLoading = $ionicLoading;
        service.$ionicModal = $ionicModal;
        service.$ionicPopup = $ionicPopup;
        service.$ionicActionSheet = $ionicActionSheet;

        service.$rootScope = $rootScope;

        return service;
    }]);


//AJAX server
app.service('ajaxService', ["$ionicLoading", "$http", "toastService", function ($ionicLoading, $http, toastService) {

    var service = {};

    var sendAJAX = function (url, method, body, cb, st) {
        method = method.toLocaleUpperCase();
        if (HX_CONFIG.debug) {
            console.log("--------------------------------准备发送AJAX----------------------------------");
            console.log("HOST：", HX_CONFIG.HOST);
            console.log("URL：", url);
            console.log("method：", method);
            console.log("body：", body);
        }


        for (var k in body) {
            if (body.hasOwnProperty(k)) {
                if (k.indexOf("$") != -1) {
                    url.replace("{" + k + "}", body[k]);
                    delete  body[k];
                }
            }
        }

        switch (method) {
            case "GET":
                var config = {params: body};

                config["headers"] = {'X-Requested-With': 'XMLHttpRequest'};

                $http.get(HX_CONFIG.HOST + url, config).success(function (data) {
                    HX_CONFIG.debug && console.log("url=" + url, "成功", "返回结果：", data, "\n");
                    if (typeof (data) === "string") {
                        st && toastService.show("服务器返回数据格式错误！");
                        cb && cb({errCode: -9997, message: "服务器返回数据格式错误！"});
                    } else {
                        if (st) {
                            if (data.errCode && data.message) toastService.show(data.message);
                        }
                        cb && cb(data);
                    }
                }).error(function (err) {
                    HX_CONFIG.debug && console.log("url=" + url, "错误", "返回结果：err = ", err, "\n");
                    st && toastService.show("访问服务器失败！");
                    cb && cb({errCode: -9999, message: "访问服务器失败！"});
                });
                break;
            case "POST":
                $http.post(HX_CONFIG.HOST + url, body, {headers: {'X-Requested-With': 'XMLHttpRequest'}}).success(function (data) {
                    HX_CONFIG.debug && console.log("url = " + url, "成功", "返回结果：", data, "\n");
                    if (typeof (data) === "string") {
                        st && toastService.show("服务器返回数据格式错误！");
                        cb && cb({errCode: -9997, message: "服务器返回数据格式错误！"});
                    } else {
                        if (st) {
                            if (data.errCode && data.message) toastService.show(data.message);
                        }
                        cb && cb(data);
                    }
                }).error(function (err) {
                    HX_CONFIG.debug && console.log("url = " + url, "错误", "返回结果：err = ", err, "\n");
                    st && toastService.show("访问服务器失败！");
                    cb && cb({errCode: -9999, message: "访问服务器失败！"});
                });
                break;
        }
    };

    var methodMap = {
        //upload_img: {url: '/community/post/upload_img', method: "POST"}, //上传图片
        //circle_index: {url: "/community/community/index", method: "get"} //获取单个圈子首页

    };

    service.ajax = function (method, opts, cb, st) {
        st = st === undefined ? true : st;
        var mm = methodMap[method];
        if (mm) {
            sendAJAX(mm.url, mm.method, opts, cb, st);
        } else {
            //未找到方法
            HX_CONFIG.debug && console.log("url 错误", "返回结果：err = ", "无法请求，无效的请求！", "\n");
            st && toastService.show("无效的请求");
            cb && cb({errCode: -1, message: "无效的请求"})
        }
    };

    return service;
}]);





